
#include <QFile>
#include <QByteArray>
#include "comm_utils.h"
#include "task_firm_read.h"
#include "ev_cmd_type.h"

FirmwareReadTask::FirmwareReadTask(EvSerial *serial, const QString &filePath)
    : TaskCommBase(serial)
{
    m_filePath = filePath;
}

void FirmwareReadTask::run()
{
    QString mssg = QString("读取固件 ...");
    emit messageLogged(LogUtils::makeLogBin(mssg));


    mssg = QString("-- 读取固件长度 ...");
    emit messageLogged(LogUtils::makeLogBin(mssg));
    uint32_t firm_len = 0;
    int ret = callGetVersion(0, nullptr, nullptr, nullptr, nullptr, &firm_len);
    if (ret != 0) {
        mssg = QString("-- 读取固件长度失败, 错误码: %1").arg(ret);
        emit messageLogged(LogUtils::makeLogBin(mssg));
        emit finished(false);
        return;
    }
    if (firm_len == 0) {
        mssg = QString("-- 错误: 读取的固件长度为0");
        emit messageLogged(LogUtils::makeLogBin(mssg));
        emit finished(false);
        return;
    }
    mssg = QString("-- 固件长度: %1").arg(firm_len);
    emit messageLogged(LogUtils::makeLogBin(mssg));


    mssg = QString("-- 读取固件内容 ...");
    emit messageLogged(LogUtils::makeLogBin(mssg));
    QByteArray binaryData;
    uint32_t pkt_num = (firm_len - 1) / EV_CALL_OTA_DATA_LEN + 1;
    char read_buf[EV_CALL_OTA_DATA_LEN] = {0};
    for (uint32_t i = 0; i < pkt_num; i++) {
        ret = callOtaRead(i, (uint8_t *)read_buf);
        if (ret != 0) {
            mssg = QString("-- 读取固件失败, 错误码: %1").arg(ret);
            emit messageLogged(LogUtils::makeLogBin(mssg));
            emit finished(false);
            return;
        }
        emit progressUpdated(i * 100 / pkt_num);
        binaryData.append(read_buf, EV_CALL_OTA_DATA_LEN);
        // file.write(read_buf, EV_CALL_OTA_DATA_LEN);
    }


    mssg = QString("-- 写入文件 ...");
    emit messageLogged(LogUtils::makeLogBin(mssg));
    QFile file(m_filePath);
    if (!file.open(QIODevice::WriteOnly)) {
        mssg = QString("-- 写入文件失败: %1").arg(m_filePath);
        emit messageLogged(LogUtils::makeLogBin(mssg));
        emit finished(false);
        return;
    }
    file.write(binaryData);
    file.close();


    emit messageLogged(LogUtils::makeLogBin("读取固件成功"));
    emit finished(true);
}
